package x.java.tea;

import java.io.IOException;
import java.io.InputStream;

/**
 * Wrap an input stream as injector, close stream when end is reached if close
 * flag is true.
 * 
 * @author qiangli
 * 
 */
public class InputStreamInjector implements Injector {
	protected String id;
	protected InputStream in;
	protected boolean close;
	
	public InputStreamInjector(InputStream in) {
		this(in, false);
	}
	
	public InputStreamInjector(InputStream in, boolean close) {
		this.in = in;
		this.close = close;
	}

	@Override
	public void init(String id) {
		this.id = id;
	}

	@Override
	public int inject(byte[] buf) throws IOException {
		int c = in.read(buf);
		if (c == -1 && close) {
			try {
				in.close();
			} catch (Exception e) {
				//
			}
		}
		return c;
	}

	public String getId() {
		return id;
	}
}
